package com.zjw.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjw.shortlink.admin.common.constant.RedisCacheConstant;
import com.zjw.shortlink.admin.common.convention.errorcode.BaseErrorCode;
import com.zjw.shortlink.admin.common.convention.exception.ClientException;
import com.zjw.shortlink.admin.dao.entity.UserDO;
import com.zjw.shortlink.admin.dao.mapper.UserMapper;
import com.zjw.shortlink.admin.dto.req.UserLoginReqDTO;
import com.zjw.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.zjw.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.zjw.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.zjw.shortlink.admin.dto.resp.UserRealRespDTO;
import com.zjw.shortlink.admin.dto.resp.UserRespDTO;
import com.zjw.shortlink.admin.service.GroupService;
import com.zjw.shortlink.admin.service.UserService;
import org.apache.catalina.User;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    @Autowired
    private RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private GroupService groupService;

    @Override
    public Boolean isExistUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public UserRespDTO getUserByUserName(String username) {
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, username);
        return BeanUtil.copyProperties(userMapper.selectOne(eq), UserRespDTO.class);
    }

    @Override
    public UserRealRespDTO getRealUserByUserName(String username) {
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, username);
        return BeanUtil.copyProperties(userMapper.selectOne(eq), UserRealRespDTO.class);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(isExistUsername(requestParam.getUsername())) {
            throw new ClientException(BaseErrorCode.USER_NAME_EXIST_ERROR);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if(lock.tryLock()) {
                int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                if(inserted < 1) {
                    throw new ClientException(BaseErrorCode.USER_SAVE_ERROR);
                }
                groupService.saveGroup(requestParam.getUsername(), "默认分组");
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
            }
        } catch (DuplicateKeyException ex) {
            throw new ClientException(BaseErrorCode.USER_NAME_EXIST_ERROR);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        // TODO 验证当前用户名是否为登录用户
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.copyProperties(requestParam, UserDO.class), eq);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO user = baseMapper.selectOne(eq);
        if(user == null) {
            throw new ClientException("用户名不存在");
        }
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries("login_" + requestParam.getUsername());
        if(CollUtil.isNotEmpty(hasLoginMap)) {
            // 重复登录刷新Token有效期
            stringRedisTemplate.expire("login_" + requestParam.getUsername(), 30L, TimeUnit.DAYS);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_" + requestParam.getUsername(), token, JSON.toJSONString(user));
        stringRedisTemplate.expire("login_" + requestParam.getUsername(), 30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(token);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username, token)) {
            stringRedisTemplate.delete("login_" + username);
            return;
        }
        throw new ClientException("用户尚未登录");
    }
}
